<!--  -->
<template>
  <div class='content'>
    <v-ace-editor v-model:value="editText" @init="jsonFormat" mode="json5" lang="json5" :theme="theme" :options="options"
      :readonly="readOnly" :style="`height:${height}px`" class="ace-editor" />
  </div>
</template>

<script setup>
import { VAceEditor } from 'vue3-ace-editor';
import ace from "ace-builds";
import modeJsonUrl from 'ace-builds/src-noconflict/mode-json5?url'
ace.config.setModuleUrl('ace/mode/json5', modeJsonUrl)
import themeChromeUrl from 'ace-builds/src-noconflict/theme-chrome?url';
ace.config.setModuleUrl('ace/theme/chrome',themeChromeUrl);
import themeTomorrow from 'ace-builds/src-noconflict/theme-tomorrow?url'
ace.config.setModuleUrl('ace/theme/tomorrow', themeTomorrow)

const emit = defineEmits(['update:value'])
const props = defineProps({
  value: {
    type: String
  },
  theme: {
    type: String,
    // 可选值参考弃用文件
    default: 'tomorrow'
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  height: {
    type: Number,
    default: 300
  },
  options: {
    type: Object,
    default: {
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: true,
      tabSize: 2,
      showPrintMargin: false,
      fontSize: 13
    }
  }
})
// 计算属性
const editText = computed({
  get: () => {
    return props.value;
  },
  set: (e) => {
    emit('update:value', e)
  }
})


const jsonError = (e) => {
  console.log(`JSON字符串错误：${e.message}`);
}

// JSON格式化
const jsonFormat = () => {
  try {
    // emit('update:value',JSON.stringify(JSON.parse(props.value), null, 2))
    editText.value = JSON.stringify(JSON.parse(editText.value), null, 2)
  } catch (e) {
    jsonError(e)
  }
};

// JSON压缩
const jsonNoFormat = () => {
  try {
    editText.value = JSON.stringify(JSON.parse(editText.value))
  } catch (e) {
    jsonError(e)
  }
}
defineExpose({
  jsonFormat,
  jsonNoFormat
})
</script>
  

<style scoped></style>